import Taro from '@tarojs/taro'
import axios from 'axios'
import { TaroAdapter } from "axios-taro-adapter"


// 创建 axios 实例
const service = axios.create({
    // https://tapi.cysjdata.com 测试地址
    // https://gapi.cysjdata.com:8888
    // https://g.cysjdata.com 线上地址
    baseURL: 'https://g.cysjdata.com',
    timeout: 50000,
    headers: { "Content-Type": "application/json" },
    adapter: TaroAdapter,
  });


  // 请求拦截器
  service.interceptors.request.use(
  async (config) => {
    Taro.showLoading({
      title: '加载中...'
    })
    //   配置config
    try {
      var token_key_obj = Taro.getStorageSync('userData')
      if (token_key_obj) {
        let obj = token_key_obj ? JSON.parse(token_key_obj) : {token_key: null}
        config.headers.token = obj.token_key;
        return config;
      } else {return config}
    } catch (e) {
      return config;
    }
  },
    (error) => {
      return Promise.reject(error);
    }
  );

  // 响应拦截器
  service.interceptors.response.use(
    (response) => {
      Taro.hideLoading()
        const res = response.data
        // 根据返回的状态码做相应处理，例如401未授权等
        if (res.code == '904') {
          Taro.clearStorage()
          Taro.showModal({
            title: '温馨提示',
            confirmText: '去登录',
            showCancel: true,
            content: '您现在是未登录状态，请登录之后体验',
            success: (res) => {
              if (res.confirm) {
                Taro.navigateTo({
                  url: '/pages/login/index'
                })
              }
            }
          })

        }
        return res
    },
    (error) => {
      return Promise.reject(error);
    }
  );

  // 导出 axios 实例
  export default service;
